#include <stdio.h>
#include <stdlib.h>
#include "linkstack.h"



//创建
linkstack stack_create(){

   linkstack s = ( linkstack )malloc( sizeof( linknode ) );
   if( s== NULL )
   {
       printf("mallloc failed\n");
       return NULL;
   }

   s->data = 0;
   s->next = NULL;

   return s;
}

//进栈
int stack_push( linkstack s, data_t value ){

    if( s == NULL )
    {
	printf("s is NULL\n");
	return -1;
    }

    linkstack p = ( linkstack )malloc( sizeof( linknode ) );
    if( p == NULL )
    {
	printf("malloc failed\n");
	return -1;
    }

    p->data = value;
    p->next = s->next;
    s->next = p;
}

//出栈
data_t stack_pop( linkstack s ){

    if( s == NULL )
    {
	printf("s is NULL\n");
	return -1;
    }

    if( s->next == NULL )
    {
	printf("stack not data");
	return -1;
    }
    
    linkstack p = s->next;
    data_t val = p->data;

    s->next = p->next;
    free( p );
    p = NULL;

    return val;
}

//判断是否为空
int stack_empty( linkstack s ){
    
    if( s == NULL )
    {
	printf("s is NULL\n");
	return -1;
    }

    return s->next == NULL ? 1 : 0;
}

//栈顶元素
data_t stack_top( linkstack s ){

    if( s == NULL )
    {
	printf("s is NULL\n");
	return -1;
    }

    if( s->next == NULL )
    {
	printf("stack not data");
	return -1;
    }

    return s->next->data;
}


//释放栈
linkstack stack_free( linkstack s ){

    if( s == NULL )
    {
	printf("s is NULL\n");
	return NULL;
    }

    linkstack p;
    while( s != NULL )
    { 
	p = s;
	free(p);
	s = s->next;
    }

    return NULL;

}
